from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.utils import timezone
from django.db.models import Q, Count
from .models import TodoItem, Category


def index(request):
    """主页视图 - 显示所有待办事项"""
    # 获取筛选参数
    filter_type = request.GET.get('filter', 'all')
    category_id = request.GET.get('category')
    priority = request.GET.get('priority')
    search = request.GET.get('search')
    
    # 基础查询
    todos = TodoItem.objects.all()
    
    # 应用筛选
    if filter_type == 'active':
        todos = todos.filter(is_completed=False)
    elif filter_type == 'completed':
        todos = todos.filter(is_completed=True)
    elif filter_type == 'overdue':
        todos = todos.filter(
            is_completed=False,
            due_date__lt=timezone.now()
        )
    
    # 分类筛选
    if category_id:
        todos = todos.filter(category_id=category_id)
    
    # 优先级筛选
    if priority:
        todos = todos.filter(priority=priority)
    
    # 搜索
    if search:
        todos = todos.filter(
            Q(title__icontains=search) | 
            Q(description__icontains=search)
        )
    
    # 获取统计数据
    total_count = TodoItem.objects.count()
    active_count = TodoItem.objects.filter(is_completed=False).count()
    completed_count = TodoItem.objects.filter(is_completed=True).count()
    overdue_count = TodoItem.objects.filter(
        is_completed=False,
        due_date__lt=timezone.now()
    ).count()
    
    # 获取所有分类
    categories = Category.objects.annotate(
        todo_count=Count('todos')
    ).order_by('name')
    
    context = {
        'todos': todos,
        'categories': categories,
        'filter_type': filter_type,
        'selected_category': category_id,
        'selected_priority': priority,
        'search_query': search,
        'total_count': total_count,
        'active_count': active_count,
        'completed_count': completed_count,
        'overdue_count': overdue_count,
        'priority_choices': TodoItem.PRIORITY_CHOICES,
    }
    
    return render(request, 'todo/index.html', context)


def create_todo(request):
    """创建新待办事项"""
    if request.method == 'POST':
        title = request.POST.get('title')
        description = request.POST.get('description', '')
        category_id = request.POST.get('category')
        priority = request.POST.get('priority', 'medium')
        due_date = request.POST.get('due_date')
        
        if title:
            todo = TodoItem(
                title=title,
                description=description,
                priority=priority
            )
            
            if category_id:
                todo.category_id = category_id
            
            if due_date:
                todo.due_date = due_date
            
            todo.save()
            messages.success(request, f'成功创建待办事项: {title}')
        else:
            messages.error(request, '标题不能为空')
        
        return redirect('todo:index')
    
    # GET 请求
    categories = Category.objects.all()
    context = {
        'categories': categories,
        'priority_choices': TodoItem.PRIORITY_CHOICES,
    }
    return render(request, 'todo/create.html', context)


def edit_todo(request, todo_id):
    """编辑待办事项"""
    todo = get_object_or_404(TodoItem, id=todo_id)
    
    if request.method == 'POST':
        todo.title = request.POST.get('title', todo.title)
        todo.description = request.POST.get('description', '')
        todo.priority = request.POST.get('priority', 'medium')
        
        category_id = request.POST.get('category')
        if category_id:
            todo.category_id = category_id
        else:
            todo.category = None
        
        due_date = request.POST.get('due_date')
        if due_date:
            todo.due_date = due_date
        else:
            todo.due_date = None
        
        todo.save()
        messages.success(request, f'成功更新待办事项: {todo.title}')
        return redirect('todo:index')
    
    categories = Category.objects.all()
    context = {
        'todo': todo,
        'categories': categories,
        'priority_choices': TodoItem.PRIORITY_CHOICES,
    }
    return render(request, 'todo/edit.html', context)


def delete_todo(request, todo_id):
    """删除待办事项"""
    todo = get_object_or_404(TodoItem, id=todo_id)
    
    if request.method == 'POST':
        title = todo.title
        todo.delete()
        messages.success(request, f'成功删除待办事项: {title}')
    
    return redirect('todo:index')


def toggle_todo(request, todo_id):
    """切换待办事项的完成状态"""
    todo = get_object_or_404(TodoItem, id=todo_id)
    todo.is_completed = not todo.is_completed
    todo.save()
    
    if todo.is_completed:
        messages.success(request, f'已完成: {todo.title}')
    else:
        messages.info(request, f'已标记为未完成: {todo.title}')
    
    return redirect('todo:index')


def manage_categories(request):
    """管理科目分类"""
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'create':
            name = request.POST.get('name')
            color = request.POST.get('color', '#007bff')
            
            if name:
                Category.objects.create(name=name, color=color)
                messages.success(request, f'成功创建科目: {name}')
            else:
                messages.error(request, '科目名称不能为空')
        
        elif action == 'delete':
            category_id = request.POST.get('category_id')
            category = get_object_or_404(Category, id=category_id)
            name = category.name
            category.delete()
            messages.success(request, f'成功删除科目: {name}')
        
        return redirect('todo:manage_categories')
    
    categories = Category.objects.annotate(
        todo_count=Count('todos')
    ).order_by('name')
    
    context = {
        'categories': categories,
    }
    return render(request, 'todo/manage_categories.html', context)
